package com.czwj.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Value;

import net.sf.json.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Key;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 */
public class WechatUtil {
    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        return new String(
                decryptOfDiyIV(
                        Base64.decode(encryptDataB64),
                        Base64.decode(sessionKeyB64),
                        Base64.decode(ivB64)
                )
        );
    }

    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;
    
    @Value("${appid}")
	private static String appid="wx4c757d768dde9c29";
	
	@Value("${appsecret}")
	private static String appsecret="25540dfabb6f5a846eca8713c07eab36";

    private static void init(byte[] keyBytes) {
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @param ivs           自定义对称解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }
    
    public static String pushMessage(String touser,String modelcode,String formid,JSONObject data){
		try {
			String accesstoken_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
			URL url = new URL(accesstoken_url);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
	        connection.connect();
	        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        String result = "";
	        String line;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	        Map<String, Object> map = GsonUtil.getKeytoValueFromJsonObject(result);
	        String access_token = map.get("access_token").toString();
	        String message_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+access_token;
	        JSONObject params = new JSONObject();
	        params.put("touser", touser);
	        params.put("template_id", modelcode);
	        params.put("form_id", formid);
	        params.put("page", "pages/index/index");
	        params.put("data", data);
	        
	        
	        
	        byte[] postDataBytes = GsonUtil.objectToJsonStr(params).getBytes("UTF-8");

	        url = new URL(message_url);
	        connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
			connection.setConnectTimeout(2000);
			connection.setReadTimeout(5000);
			connection.setDoOutput(true);
			connection.getOutputStream().write(postDataBytes);
			 Reader in1 = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

			    StringBuilder sb = new StringBuilder();
			    for (int c; (c = in1.read()) >= 0;) {
			        sb.append((char)c);
			    }
			    in1.close();
			    connection.disconnect();
			    
			    String responseStr = sb.toString();
			    Map<String, Object> result1 = GsonUtil.getKeytoValueFromJsonObject(responseStr);
			    return result1.get("errcode").toString();
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "-1";
		}
	
    }
    
    public static JSONObject setReviewData(String data1,String data2){
        JSONObject data = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        JSONObject keyword2 = new JSONObject();
        keyword1.put("value", data1);
        keyword2.put("value", data2);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        return data;
    }
    
    public static JSONObject setReviewFailResultData(String data1,String data2,String data3,String data4,String data5,String data6){
        JSONObject data = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        JSONObject keyword2 = new JSONObject();
        JSONObject keyword3 = new JSONObject();
        JSONObject keyword4 = new JSONObject();
        JSONObject keyword5 = new JSONObject();
        JSONObject keyword6 = new JSONObject();
        keyword1.put("value", data1);
        keyword2.put("value", data2);
        keyword3.put("value", data3);
        keyword4.put("value", data4);
        keyword5.put("value", data5);
        keyword6.put("value", data6);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        data.put("keyword6", keyword6);
        return data;
    }
    
    public static JSONObject setReviewSuccessResultData(String data1,String data2,String data3,String data4,String data5){
        JSONObject data = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        JSONObject keyword2 = new JSONObject();
        JSONObject keyword3 = new JSONObject();
        JSONObject keyword4 = new JSONObject();
        JSONObject keyword5 = new JSONObject();
        keyword1.put("value", data1);
        keyword2.put("value", data2);
        keyword3.put("value", data3);
        keyword4.put("value", data4);
        keyword5.put("value", data5);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        return data;
    }

    
}
